package es.indra.druida.desktop.fileaccess;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.servlet.http.HttpSession;

import es.indra.druida.desktop.security.DesktopFileSecurity;

/**
 * The Class FileAccessService.
 */
public class FileAccessService {
	
	/**
	 * Load text file.
	 * 
	 * @param filePath
	 *            the file path
	 * @param sesion
	 *            the sesion
	 * 
	 * @return the file access response
	 */
	public FileAccessResponse loadTextFile(String filePath, HttpSession sesion)	{
		FileAccessResponse resp=new FileAccessResponse();
		try	{
			File fichero=DesktopFileSecurity.getFile(filePath, sesion);//Esto ya lanza excepciones con los errores de seguridad.
			BufferedReader br = new BufferedReader(new FileReader(fichero));
			StringBuffer sf=new StringBuffer();
			int caracter;
			while ((caracter = br.read()) != -1) {
				sf.append((char)caracter);
			}
			resp.setTextContent(sf.toString());
			br.close();
		} catch (Exception e){
			resp.setErrorDeOperacion(true);
			resp.setExcepcionError(e);
		}
		return resp;
	}	
	
	/**
	 * Save text file.
	 * 
	 * @param filePath
	 *            the file path
	 * @param txtContent
	 *            the txt content
	 * @param sesion
	 *            the sesion
	 * 
	 * @return the file access response
	 */
	public FileAccessResponse saveTextFile(String filePath, String txtContent, HttpSession sesion)	{
		FileAccessResponse resp=new FileAccessResponse();
		try	{
			File fichero=DesktopFileSecurity.getFile(filePath, sesion);//Esto ya lanza excepciones con los errores de seguridad.
			BufferedWriter bw = new BufferedWriter(new FileWriter(fichero));
			bw.write(txtContent);
			bw.close();
		} catch (Exception e){
			resp.setErrorDeOperacion(true);
			resp.setExcepcionError(e);
		}
		return resp;
	}
	
}
